package com.fxl.majiang.service.impl;

import com.fxl.majiang.room.Player;
import com.fxl.majiang.room.Room;
import com.fxl.majiang.room.RoomManager;
import com.fxl.majiang.service.RoomService;
import org.springframework.stereotype.Service;

/**
 * @author fengxinglei
 * @date 2022/8/16 16:44
 * @description TODO
 */
@Service
public class RoomServiceImpl implements RoomService {
    @Override
    public String distribution(String userId) {
        // 先查询用户是否已经房间
        Room room = RoomManager.getUserRoom(userId);
        if (room == null) {
            // 分配房间
            return RoomManager.distribution(userId);
        } else {
            // 判定房间内是否有该成员，防止乌龙
            Player player = room.getPlayer(userId);
            if (player != null) {
                return room.getId();
            } else {
                // 如果没有，尝试加入
                if (room.canJoin()) {
                    return room.join(userId);
                } else {
                    // 如果不能加入，则从房间中移除
                    RoomManager.removeFromRoom(userId);
                    return null;
                }
            }
        }
    }
}
